package net.keebook.webapp.bean;

import java.io.IOException;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import net.keebook.webapp.dao.GroupDao;
import net.keebook.webapp.dao.KeeBookDao;
import net.keebook.webapp.entity.ItemGroup;
import net.keebook.webapp.model.SessionModel;
import net.keebook.webapp.util.AccessRight;
import net.keebook.webapp.util.Messages;


@ManagedBean
@RequestScoped
public class ListGroupsBean {
	@Inject
	private GroupDao groupDao;
	@Inject
	private KeeBookDao keeBookDao;
	private SessionModel sessionModel;
	
	@PostConstruct
	public void init() throws IOException {
		setSessionModel(SessionModel.getInstance(FacesContext.getCurrentInstance()));
		
		HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
		String exposableId = request.getParameter("delete");
		if (exposableId != null && !"".equals(exposableId)) {
			if (!getKeeBookDao().getKeeBookAccess(getSessionModel(), AccessRight.READ_WRITE))  {
				Logger.getLogger(this.getClass()).warn("Forbidden access to bean from userId="+getSessionModel().getUserId());
				FacesContext.getCurrentInstance().getExternalContext().redirect("403.xhtml");
				return;
			}
			
			ItemGroup group = getGroupDao().get(exposableId);
			if (group != null) {
				if (getGroupDao().canAccess(getSessionModel().getUserId(), group.getId())) {
					getGroupDao().delete(group);
					FacesContext.getCurrentInstance().getExternalContext().redirect("listgroups.xhtml?msg="+Messages.ITEM_DELETED);
					return;
				}
			}
			FacesContext.getCurrentInstance().getExternalContext().redirect("listgroups.xhtml?msg="+Messages.ITEM_DELETE_FAILED);
		}
	}
	
	public List<ItemGroup> getGroups() {
		return getGroupDao().getList(getSessionModel().getUserId(), getSessionModel().getKeeBookId());
	}

	public GroupDao getGroupDao() {
		return groupDao;
	}

	public void setGroupDao(GroupDao groupDao) {
		this.groupDao = groupDao;
	}

	public SessionModel getSessionModel() {
		return sessionModel;
	}

	public void setSessionModel(SessionModel sessionModel) {
		this.sessionModel = sessionModel;
	}

	public KeeBookDao getKeeBookDao() {
		return keeBookDao;
	}

	public void setKeeBookDao(KeeBookDao keeBookDao) {
		this.keeBookDao = keeBookDao;
	}
}
